import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { message } from 'antd';

interface Exam {
  id: string;
  title: string;
  course: string;
  courseId: string;
  time: string;
  duration: number;
  location: string;
  type: "闭卷" | "开卷" | "上机考试" | "答辩";
  status: "未开始" | "进行中" | "已完成" | "已结束" | "已提交";
  score?: number;
  fullScore: number;
  description?: string;
  knowledgePoints?: string[];
  submittedAt?: string;
  timeSpent?: number;
  isInProgress?: boolean;
}

interface ExamContextType {
  exams: Exam[];
  upcomingExams: Exam[];
  completedExams: Exam[];
  loading: boolean;
  refreshExams: () => void;
  startExam: (examId: string) => void;
  submitExam: (examId: string, answers: any, timeSpent: number) => void;
  saveAndExit: (examId: string, answers: any) => void;
  getExamById: (examId: string) => Exam | undefined;
  updateExamStatus: (examId: string, status: Exam['status'], data?: Partial<Exam>) => void;
}

const ExamContext = createContext<ExamContextType | undefined>(undefined);

export const useExamContext = () => {
  const context = useContext(ExamContext);
  if (!context) {
    throw new Error('useExamContext must be used within an ExamProvider');
  }
  return context;
};

interface ExamProviderProps {
  children: ReactNode;
}

export const ExamProvider: React.FC<ExamProviderProps> = ({ children }) => {
  const [exams, setExams] = useState<Exam[]>([]);
  const [loading, setLoading] = useState(true);

  // 初始考试数据
  const initialExams: Exam[] = [
    {
      id: "1",
      title: "数据结构期中考试",
      course: "数据结构与算法",
      courseId: "cs101",
      time: "2024-12-26 14:00",
      duration: 120,
      location: "A301",
      type: "闭卷",
      status: "未开始",
      fullScore: 100,
      description: "本次考试涵盖线性表、栈、队列、树、图等基础数据结构，以及相关算法的实现和应用。",
      knowledgePoints: ["线性表", "栈和队列", "树结构", "图算法", "排序算法"]
    },
    {
      id: "2",
      title: "数据库系统期末考试",
      course: "数据库系统原理",
      courseId: "cs201",
      time: "2025-01-15 09:00",
      duration: 120,
      location: "B205",
      type: "闭卷",
      status: "未开始",
      fullScore: 100,
      description: "期末考试将全面考察数据库系统的基本概念、SQL语言、数据库设计和优化等内容。",
      knowledgePoints: ["关系数据库", "SQL语言", "数据库设计", "事务管理", "查询优化"]
    },
    {
      id: "3",
      title: "计算机网络实验考核",
      course: "计算机网络",
      courseId: "cs301",
      time: "2025-01-10 14:00",
      duration: 90,
      location: "C401",
      type: "上机考试",
      status: "进行中",
      fullScore: 100,
      description: "上机实验考核，包括网络配置、协议分析、网络编程等实践内容。",
      knowledgePoints: ["网络协议", "网络配置", "网络编程", "协议分析"],
      isInProgress: true
    },
    {
      id: "4",
      title: "计算机网络期中考试",
      course: "计算机网络",
      courseId: "cs301",
      time: "2024-12-20 14:00",
      duration: 90,
      location: "C401",
      type: "闭卷",
      score: 85,
      status: "已完成",
      fullScore: 100,
      submittedAt: "2024-12-20 15:25:00",
      timeSpent: 85,
      description: "期中考试主要考察网络基础概念和TCP/IP协议栈。",
      knowledgePoints: ["网络基础", "TCP/IP协议", "网络层", "传输层"]
    },
    {
      id: "5",
      title: "计算机组成原理期中考试",
      course: "计算机组成原理",
      courseId: "cs401",
      time: "2024-12-15 14:00",
      duration: 120,
      location: "D201",
      type: "闭卷",
      score: 95,
      status: "已完成",
      fullScore: 100,
      submittedAt: "2024-12-15 15:45:00",
      timeSpent: 105,
      description: "期中考试涵盖计算机系统的基本组成和工作原理。",
      knowledgePoints: ["CPU结构", "存储器", "指令系统", "总线系统"]
    },
    {
      id: "6",
      title: "操作系统原理期中考试",
      course: "操作系统原理",
      courseId: "cs501",
      time: "2024-12-10 14:00",
      duration: 120,
      location: "E301",
      type: "闭卷",
      score: 87,
      status: "已完成",
      fullScore: 100,
      submittedAt: "2024-12-10 15:50:00",
      timeSpent: 110,
      description: "期中考试重点考察进程管理、内存管理和文件系统。",
      knowledgePoints: ["进程管理", "内存管理", "文件系统", "设备管理"]
    }
  ];

  // 加载考试数据
  const loadExams = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 从localStorage获取考试状态更新
      const examUpdates = localStorage.getItem('exam_updates');
      let updatedExams = [...initialExams];
      
      if (examUpdates) {
        const updates = JSON.parse(examUpdates);
        updatedExams = updatedExams.map(exam => {
          const update = updates[exam.id];
          if (update) {
            return { ...exam, ...update };
          }
          return exam;
        });
      }
      
      setExams(updatedExams);
    } catch (error) {
      console.error("加载考试数据失败:", error);
      message.error("加载考试数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 刷新考试列表
  const refreshExams = () => {
    loadExams();
  };

  // 开始考试
  const startExam = (examId: string) => {
    setExams(prevExams => 
      prevExams.map(exam => 
        exam.id === examId 
          ? { ...exam, status: "进行中" as const, isInProgress: true }
          : exam
      )
    );
    
    // 保存到localStorage
    const examUpdates = JSON.parse(localStorage.getItem('exam_updates') || '{}');
    examUpdates[examId] = { status: "进行中", isInProgress: true };
    localStorage.setItem('exam_updates', JSON.stringify(examUpdates));
    
    message.success("考试已开始");
  };

  // 提交考试
  const submitExam = (examId: string, answers: any, timeSpent: number) => {
    const now = new Date().toISOString();
    
    setExams(prevExams => 
      prevExams.map(exam => 
        exam.id === examId 
          ? { 
              ...exam, 
              status: "已完成" as const, 
              isInProgress: false,
              submittedAt: now,
              timeSpent: timeSpent,
              // 模拟评分（实际应该调用后端API）
              score: Math.floor(Math.random() * 30) + 70 // 70-100分
            }
          : exam
      )
    );
    
    // 保存到localStorage
    const examUpdates = JSON.parse(localStorage.getItem('exam_updates') || '{}');
    examUpdates[examId] = { 
      status: "已完成", 
      isInProgress: false,
      submittedAt: now,
      timeSpent: timeSpent,
      score: Math.floor(Math.random() * 30) + 70
    };
    localStorage.setItem('exam_updates', JSON.stringify(examUpdates));
    
    // 清除考试状态
    localStorage.removeItem(`exam_${examId}_start_time`);
    localStorage.removeItem(`exam_${examId}_answers`);
    
    message.success("考试提交成功！");
  };

  // 保存并退出
  const saveAndExit = (examId: string, answers: any) => {
    setExams(prevExams => 
      prevExams.map(exam => 
        exam.id === examId 
          ? { ...exam, status: "已提交" as const, isInProgress: true }
          : exam
      )
    );
    
    // 保存到localStorage
    const examUpdates = JSON.parse(localStorage.getItem('exam_updates') || '{}');
    examUpdates[examId] = { status: "已提交", isInProgress: true };
    localStorage.setItem('exam_updates', JSON.stringify(examUpdates));
    
    // 保存答案
    localStorage.setItem(`exam_${examId}_answers`, JSON.stringify(answers));
    
    message.success("答案已保存，您可以稍后继续考试");
  };

  // 根据ID获取考试
  const getExamById = (examId: string) => {
    return exams.find(exam => exam.id === examId);
  };

  // 更新考试状态
  const updateExamStatus = (examId: string, status: Exam['status'], data?: Partial<Exam>) => {
    setExams(prevExams => 
      prevExams.map(exam => 
        exam.id === examId 
          ? { ...exam, status, ...data }
          : exam
      )
    );
    
    // 保存到localStorage
    const examUpdates = JSON.parse(localStorage.getItem('exam_updates') || '{}');
    examUpdates[examId] = { status, ...data };
    localStorage.setItem('exam_updates', JSON.stringify(examUpdates));
  };

  // 计算即将考试和已完成考试
  const upcomingExams = exams.filter(exam => 
    exam.status === "未开始" || exam.status === "进行中" || exam.status === "已提交"
  );
  
  const completedExams = exams.filter(exam => exam.status === "已完成");

  useEffect(() => {
    loadExams();
  }, []);

  const value: ExamContextType = {
    exams,
    upcomingExams,
    completedExams,
    loading,
    refreshExams,
    startExam,
    submitExam,
    saveAndExit,
    getExamById,
    updateExamStatus,
  };

  return (
    <ExamContext.Provider value={value}>
      {children}
    </ExamContext.Provider>
  );
}; 